class Project < ActiveRecord::Base
  attr_accessible :title, :started_on, :completed_on, :description_markdown, :location, :total_amount
  
  has_many :milestones
  has_many :tasks, :through => :milestones
  has_many :change_orders
  has_many :payments
  
  has_and_belongs_to_many   :tags, 
                            :join_table   => "tagged_items", 
                            :foreign_key  => "taggable_id", 
                            :conditions   => "taggable_type = '#{self.class_name}'", 
                            :insert_sql   => 'INSERT INTO tagged_items (taggable_id,tag_id,taggable_type) VALUES (#{id}, #{record.id}, \'#{self.class}\');',
                            :after_add    => :increment_tag_count, 
                            :after_remove => :decrement_tag_count
  
  
  before_save   :markup_description, :if => Proc.new { |b| b.description_markdown_changed? }
  
  
  def sub_contractors
    self.tasks.collect{|t| t.sub_contractor}.uniq
  end
  
  def percent_done
    ((self.tasks.select{|t| t.status_code == 3}.size.to_f / self.tasks.size.to_f) * 100.0).to_i.to_s + "%"
  end
  
  protected
  
  def increment_tag_count(tag)
    tag.count += 1
    tag.save
  end
  
  def decrement_tag_count(tag)
    # tag arrive at this method as readonly so I have to instantiate a new Tag object.  geh...
    t = Tag.find(tag.id)
    t.count -= 1
    t.save 
  end

  def markup_description
    self.description_html = BlueCloth::new(self.description_markdown).to_html
  end
  
end
